package com.speech.activity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.util.Base64;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog;
import com.speech.AppConfig;
import com.speech.MyApplication;
import com.speech.R;
import com.speech.constant.PrefsConstant;
import com.speech.db.SharedPreferenceHelper;
import com.speech.entity.BaseEntity;
import com.speech.entity.UserInfo;
import com.speech.http.BaseCallback;
import com.speech.net.BasicCallBack;
//import com.speech.net.HttpCommunicationManager;
import com.speech.net.constant.EnumReqestActionCode;
import com.speech.net.entity.MessageC2S;
import com.speech.net.entity.MessageC2SBuilder;
import com.speech.net.entity.MessageS2C;
import com.speech.net.request.UserInfo_Data;
import com.speech.net.result.Property_Result;
import com.speech.result.Result;
import com.speech.utils.DeviceUtil;
import com.speech.utils.JsonProcessor;
import com.speech.utils.PropertyAndUserInfoHolder;
import com.speech.utils.TitleBuilder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Call;

public class EditMineEntranceActivity extends BaseActivity implements View.OnClickListener {

    private ConstraintLayout cl_head;
    private ConstraintLayout cl_nickname;

    private SimpleDraweeView sdv_head;
    private TextView tv_nickname;

    private SweetAlertDialog dialog;
    private SweetAlertDialog dialog1;
    private SweetAlertDialog dialog2;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_mine_entrance);

        EasyPermissions.requestPermissions(this, "用于上传头像", 111, Manifest.permission.READ_EXTERNAL_STORAGE);

        _initView();


    }

    private void _initView() {
        new TitleBuilder(this).setTitleText("个人资料");

        sdv_head = findViewById(R.id.sdv_edit_mine_head);

        tv_nickname = findViewById(R.id.tv_edit_mine_nickname);

        cl_head = findViewById(R.id.cl_edit_mine_info_head);
        cl_nickname = findViewById(R.id.cl_edit_mine_info_nickname);

        cl_head.setOnClickListener(this);
        cl_nickname.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cl_edit_mine_info_head:
                //TODO:上传头像

                Intent intent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 100);

                break;
            case R.id.cl_edit_mine_info_nickname:
                startActivity(new Intent(EditMineEntranceActivity.this, EditNickNameActivity.class));
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppConfig.URI_HEAD_PICTURE != null) {
            sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
        }

        tv_nickname.setText(PropertyAndUserInfoHolder.getStrNickName(this));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //在相册里面选择好相片之后调回到现在的这个activity中
        switch (requestCode) {
            case 100://这里的requestCode是我自己设置的，就是确定返回到那个Activity的标志
                if (resultCode == RESULT_OK) {//resultcode是setResult里面设置的code值
                    try {
//                        dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
//                        dialog.setTitleText("上传中");
//                        dialog.setCancelable(false);
//                        dialog.show();

                        Uri selectedImage = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);  //获取照片路径
                        cursor.close();

//                        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(EditMineEntranceActivity.this,PrefsConstant.FILE_USER_INFO);


//                        final Bitmap bitmap = BitmapFactory.decodeFile(path);

                        //转成base64
//                        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

                        //TODO:图片压缩，现在采用的是默认的
//                        int quality = 100;
//                        Matrix matrix = new Matrix();
//                        matrix.setScale(0.6f,0.6f);
//                        Bitmap bp_small = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);

//                        Bitmap bitmap_compressed = compressImage(bitmap);
//                        bitmap_compressed.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//                        bitmap.compress(Bitmap.CompressFormat.JPEG, 10, baos);

//                        baos.close();
//                        byte[] buffer = baos.toByteArray();
//                        byte[] buffer = compressImage(bitmap);
//
//                        String str_base64 = Base64.encodeToString(buffer, 0, buffer.length, Base64.NO_WRAP);
//                        UserInfo_Data userInfo_data = new UserInfo_Data();
//                        userInfo_data.strUserPortrait = str_base64;

                        //TODO：上传头像接口
//                        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(EditMineEntranceActivity.this, EnumReqestActionCode.设置头像, JsonProcessor.StcGetJson(userInfo_data));
//                        String json = JsonProcessor.StcGetJson(msg_c2s);
//                        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(EditMineEntranceActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//                            @Override
//                            public void success(MessageS2C msg_s2c) {
//                                loding_dialog.dismiss();
//
//                                Property_Result property_result = JsonProcessor.StcGetObject(Property_Result.class, msg_s2c.strData);
//                                PropertyAndUserInfoHolder.update(property_result);
//                                new SweetAlertDialog(EditMineEntranceActivity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText("头像上传成功")
//                                        .setConfirmText("OK")
//                                        .show();
//
//                                AppConfig.URI_HEAD_PICTURE = null;
//
//                                //TODO 头像
//                                //重新访问服务器获取上传头像，为了统一之后的保存路径
//                                _get_user_head();
////                                AppConfig.URI_HEAD_PICTURE = Uri.parse(MediaStore.Images.Media.insertImage(EditMineEntranceActivity.this.getContentResolver(), bitmap, null, null));
////                                if (AppConfig.URI_HEAD_PICTURE != null) {
////                                    AppConfig.STATE_INIT = false;
////                                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
////                                }
//                            }
//
//                            @Override
//                            public void fail(MessageS2C msg_s2c) {
//                                loding_dialog.dismiss();
//                                new SweetAlertDialog(EditMineEntranceActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText("图片太大啦")
//                                        .setContentText("图片大小不能超过4M")
//                                        .setConfirmText("OK")
//                                        .show();
//                            }
//                        }));


                        String uid,token;
                        SharedPreferenceHelper spf = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
                        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
                        uid = lUID;
                        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
                        token = lToken;

                        File file = new File(path);
                        RequestBody uidBody = RequestBody.create(MediaType.parse("text/plain"), uid);
                        RequestBody tokenBody = RequestBody.create(MediaType.parse("text/plain"), token);
                        RequestBody deciceIdBody = RequestBody.create(MediaType.parse("text/plain"), DeviceUtil.getDeviceID(EditMineEntranceActivity.this));
//                        RequestBody imageBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
                        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("imgfile", file.getName(), imageBody);

                        Call<Result<BaseEntity>> call = MyApplication.getInstance().getApiService()
                                .uploadHead(uidBody,tokenBody,deciceIdBody,imageBodyPart);
                        call.enqueue(new BaseCallback<BaseEntity>() {
                            @Override
                            public void onSuccess(BaseEntity baseEntity) {
                                dialog.dismiss();
////
//                                Property_Result property_result = JsonProcessor.StcGetObject(Property_Result.class, baseEntity.getContent());
//                                PropertyAndUserInfoHolder.update(property_result);
//                                dialog2 = new SweetAlertDialog(EditMineEntranceActivity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText("头像上传成功")
//                                        .setConfirmText("OK");
//                                        dialog2.show();
//
//                                AppConfig.URI_HEAD_PICTURE = null;

                                //TODO 头像
                                //重新访问服务器获取上传头像，为了统一之后的保存路径
//                                _get_user_head();
//                                AppConfig.URI_HEAD_PICTURE = Uri.parse(MediaStore.Images.Media.insertImage(EditMineEntranceActivity.this.getContentResolver(), bitmap, null, null));
//                                if (AppConfig.URI_HEAD_PICTURE != null) {
//                                    AppConfig.STATE_INIT = false;
//                                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
//                                }
                            }

                            @Override
                            public void onAbnormal(String msg) {
//                                dialog.dismiss();
//                                dialog1 = new SweetAlertDialog(EditMineEntranceActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText("图片太大啦")
//                                        .setContentText("图片大小不能超过4M")
//                                        .setConfirmText("OK");
//                                dialog1.show();
                            }

                            @Override
                            public void onFailure(String msg) {
//                                dialog.dismiss();
//                                dialog1 = new SweetAlertDialog(EditMineEntranceActivity.this, SweetAlertDialog.ERROR_TYPE)
//                                        .setTitleText("图片太大啦")
//                                        .setContentText("图片大小不能超过4M")
//                                        .setConfirmText("OK");
//                                dialog1.show();
                            }
                        });

//                        SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_HEAD_PICTURE_BASE64, str_base64);


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    private void _get_user_head() {
        //TODO: 接口请求 用户首页个人信息
//        MessageC2S msg_c2s = MessageC2SBuilder.buildGeneral_MessageC2S(EditMineEntranceActivity.this, EnumReqestActionCode.获得用户信息, null);
//        String json = JsonProcessor.StcGetJson(msg_c2s);
//        HttpCommunicationManager.getInstance().doPost(json, new BasicCallBack(EditMineEntranceActivity.this, json, new BasicCallBack.BasicCallBackListener() {
//            @Override
//            public void success(MessageS2C msg_s2c) {
//                UserInfo_Data userInfo = JsonProcessor.StcGetObject(UserInfo_Data.class, msg_s2c.strData);
//
//                SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(EditMineEntranceActivity.this, PrefsConstant.FILE_USER_INFO);
//
//                if (userInfo.strUserPortrait != null && userInfo.strUserPortrait.length() > 10) {
//                    byte[] bytes = Base64.decode(userInfo.strUserPortrait, Base64.NO_WRAP);
//
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
//
//                    if (AppConfig.URI_HEAD_PICTURE == null) {
//                        String strImgUrl = MediaStore.Images.Media.insertImage(EditMineEntranceActivity.this.getContentResolver(), bitmap, null, null);
//                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,strImgUrl);
//                    }
//
//                    String strImgUrl = (String) spf_helper.getData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,SharedPreferenceHelper.STR_TYPE_DEFAULT);
//                    AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);
//
//                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);
//
//                }
//
//            }
//
//            @Override
//            public void fail(MessageS2C msg_s2c) {
//
//            }
//        }));


        String uid,token;
        SharedPreferenceHelper spf = new SharedPreferenceHelper(this, PrefsConstant.FILE_USER_INFO);
        String lUID = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_UID, "");
        uid = lUID;
        String lToken = (String) spf.getData(PrefsConstant.KEY_USER_INFO_LONG_TOKEN, "");
        token = lToken;
        Call<Result<UserInfo>> call = MyApplication.getInstance().getApiService()
                .userInfo(uid, DeviceUtil.getDeviceID(this),token);
        call.enqueue(new BaseCallback<UserInfo>() {
            @Override
            public void onSuccess(UserInfo baseEntity) {
//                UserInfo_Data userInfo = JsonProcessor.StcGetObject(UserInfo_Data.class, baseEntity.getContent());
//
                SharedPreferenceHelper spf_helper = new SharedPreferenceHelper(EditMineEntranceActivity.this, PrefsConstant.FILE_USER_INFO);

//                if (userInfo.strUserPortrait != null && userInfo.strUserPortrait.length() > 10) {
                    byte[] bytes = Base64.decode(baseEntity.getUser_portrait(), Base64.NO_WRAP);

                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    if (AppConfig.URI_HEAD_PICTURE == null) {
                        String strImgUrl = MediaStore.Images.Media.insertImage(EditMineEntranceActivity.this.getContentResolver(), bitmap, null, null);
                        spf_helper.putData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,strImgUrl);
                    }

                    String strImgUrl = (String) spf_helper.getData(PrefsConstant.KEY_USER_INFO_HEAD_LOCAL_URL_FOR_URI,SharedPreferenceHelper.STR_TYPE_DEFAULT);
                    AppConfig.URI_HEAD_PICTURE = Uri.parse(strImgUrl);

                    sdv_head.setImageURI(AppConfig.URI_HEAD_PICTURE);

//                }
            }

            @Override
            public void onAbnormal(String msg) {

            }

            @Override
            public void onFailure(String msg) {

            }
        });
    }

    public byte[] compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 >  500 && options>0) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 5;// 每次都减少5
        }
//        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
//        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return baos.toByteArray();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null){
            dialog.dismissWithAnimation();
        }
        if (dialog1 != null){
            dialog1.dismissWithAnimation();
        }
        if (dialog2 != null){
            dialog2.dismissWithAnimation();
        }
    }
}
